package com.extweb4j.web.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import com.extweb4j.core.anno.AuthAnno;
import com.extweb4j.core.anno.Log;
import com.extweb4j.core.controller.ExtController;
import com.extweb4j.core.enums.RowStatus;
import com.extweb4j.core.kit.ExtKit;
import com.extweb4j.core.kit.LoginKit;
import com.extweb4j.core.model.ExtUser;
import com.extweb4j.core.model.ExtVote;
import com.extweb4j.core.model.ExtVoteLog;
import com.extweb4j.core.model.ExtVoteOption;
import com.extweb4j.core.model.ExtVoteRole;
import com.extweb4j.web.bean.RadioBean;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

/**
 * 投票控制器
 * 
 * @author Administrator
 *
 */
public class VoteController extends ExtController {

	@AuthAnno
	public void list() {
		// 这里的vote_id是供optionlist用的（临时解决方法）
		String vote_id = getPara("vote_id");
		if (!StringUtils.isBlank(vote_id)) {
			setSessionAttr("vote_id", vote_id);
		}

		int page = getParaToInt("page");
		int limit = getParaToInt("limit");
		String keywords = getPara("keywords");
		String where = "status != ?";
		Object[] parmas = new Object[] { RowStatus.删除.getState() };
		String sort = "create_time";
		Page<ExtVote> pageData = ExtVote.dao.pageDataBy(page, limit, keywords,
				sort, "DESC", where, parmas);
		renderJson(pageData);
	}

	@Log("新建投票")
	@AuthAnno
	@Before(Tx.class)
	public void add() {
		ExtVote vote = getExtModel(ExtVote.class);
		vote.set("id", ExtKit.UUID());
		vote.set("create_time", new Timestamp(new Date().getTime()));
		vote.set("status", RowStatus.启用.getState());
		vote.save();
		// 绑定角色
		String[] roleIds = getParaValues("role_id");

		if (ArrayUtils.isEmpty(roleIds)) {
			throw new RuntimeException("无效的角色");
		}
		for (String roleId : roleIds) {
			ExtVoteRole eur = new ExtVoteRole();
			eur.set("id", ExtKit.UUID());
			eur.set("vote_id", vote.getStr("id"));
			eur.set("role_id", roleId);
			eur.save();
		}
		success();
	}

	@Log("编辑投票")
	@AuthAnno
	@Before(Tx.class)
	public void edit() {
		ExtVote vote = getExtModel(ExtVote.class);
		vote.update();
		// 绑定角色
		String[] roleIds = getParaValues("role_id");

		if (ArrayUtils.isEmpty(roleIds)) {
			throw new RuntimeException("无效的角色");
		}
		ExtVoteRole.dao.deleteByAttr("vote_id", vote.getStr("id"));
		for (String roleId : roleIds) {
			ExtVoteRole eur = new ExtVoteRole();
			eur.set("id", ExtKit.UUID());
			eur.set("vote_id", vote.getStr("id"));
			eur.set("role_id", roleId);
			eur.save();
		}
		success();
	}

	@Log("删除投票")
	@AuthAnno
	@Before(Tx.class)
	public void delete() {
		ExtVote vote = getExtModel(ExtVote.class);
		if (vote == null) {
			throw new RuntimeException("要删除的投票记录不存在");
		}
		vote.set("status", RowStatus.删除.getState());
		vote.update();
		success();
	}

	/**
	 * 根据Id获取一条记录，编辑
	 */
	public void get() {
		ExtVote vote = ExtVote.dao.findById(getPara("id"));
		List<ExtVoteRole> Roles = ExtVoteRole.dao.findByAttr("vote_id",
				vote.getStr("id"));
		List<String> roleIds = new ArrayList<String>();
		for (ExtVoteRole ext : Roles) {
			roleIds.add(ext.getStr("role_id"));
		}
		vote.put("role_id", roleIds);
		renderJson(new Record().set("success", true).set("data", vote));
	}

	// ====================用户投票==========================================================
	@AuthAnno
	public void logList() {
		String vote_id = getSessionAttr("vote_id");
		int page = getParaToInt("page");
		int limit = getParaToInt("limit");
		String keywords = getPara("keywords");
		String where = "vote_id = ?";
		Object[] parmas = new Object[] { vote_id };
		String sort = "`create_time`";
		Page<ExtVoteLog> pageData = ExtVoteLog.dao.pageDataBy(page, limit,
				keywords, sort, "DESC", where, parmas);
		for (ExtVoteLog log : pageData.getList()) {
			log.set("user_id", ExtUser.dao.getNameById(log.getStr("user_id")));
			log.set("option_id",ExtVoteOption.dao.getNameById(log.getStr("option_id")));
		}
		renderJson(pageData);
	}

	@Log("用户投票")
	@Before(Tx.class)
	public void userVote() {
		String vote_id = getSessionAttr("vote_id");
		String option_id = getPara("option_id");

		ExtUser user = LoginKit.getSessionUser(getRequest());
		ExtVote vote = ExtVote.dao.findById(vote_id);
		// 投票条件判断
		if (!ExtVoteRole.dao.isAuth(vote_id, user.getId())) {
			error("您没有投票的权限");
		} else if (option_id.equals("undefined")) {
			error("请选择投票选项");
		} else if (vote.getDate("start_time").getTime() > new Date().getTime()) {
			error("还未到投票时间");
		} else if (vote.getDate("end_time").getTime() < new Date().getTime()) {
			error("投票时间已过");
		} else if (isVoted(vote_id, user.getId())) {
			error("您已经投过票");
		} else {
			ExtVoteLog vl = new ExtVoteLog();
			vl.set("id", ExtKit.UUID());
			vl.set("vote_id", vote_id);
			vl.set("user_id", user.getId());
			vl.set("option_id", option_id);
			vl.set("create_time", new Timestamp(new Date().getTime()));
			if (vl.save()) {
				synchronized (this) {
					ExtVoteOption option = ExtVoteOption.dao
							.findById(option_id);
					vote.set("vote_count", vote.getLong("vote_count") + 1);
					option.set("opt_count", option.getLong("opt_count") + 1);
					// 保存失败则删除投票记录
					if (!vote.update() || !option.update()) {
						vl.delete();
						error("投票失败，请重试");
					} else {
						success("投票成功");
					}
				}
			}
		}
	}

	public boolean isVoted(String vote_id, String user_id) {
		ExtVoteLog log = ExtVoteLog.dao.findFirstByAttr("vote_id", vote_id);
		if (log == null) {
			return false;
		} else if (log.getStr("user_id").equals(user_id)) {
			return true;
		}
		return false;
	}

	// ==================================投票选项功能========================================
	/**
	 * 显示投票选项
	 */
	@AuthAnno
	public void optionlist() {

		String vote_id = getSessionAttr("vote_id");
		int page = getParaToInt("page");
		int limit = getParaToInt("limit");
		String keywords = getPara("keywords");
		String where = "vote_id = ?";
		Object[] parmas = new Object[] { vote_id };
		String sort = "`opt_count`";
		Page<ExtVoteOption> pageData = ExtVoteOption.dao.pageDataBy(page,
				limit, keywords, sort, "DESC", where, parmas);
		renderJson(pageData);
	}

	@Log("手动增加投票选项")
	@AuthAnno
	@Before(Tx.class)
	public void addOption() {
		ExtVoteOption option = getExtModel(ExtVoteOption.class);
		String vote_id = getSessionAttr("vote_id");
		option.set("id", ExtKit.UUID());
		option.set("vote_id", vote_id);
		option.save();
		success();
	}

	@Log("编辑投票选项")
	@AuthAnno
	@Before(Tx.class)
	public void editOption() {
		ExtVoteOption option = getExtModel(ExtVoteOption.class);
		if(ExtVoteLog.dao.isVoted(option.getStr("id"))){
			error("该选项已被投过票，无法编辑");
		}else{
			option.update();
			success();
		}
		
	}

	@Log("删除投票选项")
	@AuthAnno
	@Before(Tx.class)
	public void delOption() {
		ExtVoteOption option = getExtModel(ExtVoteOption.class);
		if (option == null) {
			throw new RuntimeException("要删除的投票选项不存在");
		}else if(ExtVoteLog.dao.isVoted(option.getStr("id"))){
			error("该选项已被投过票，无法删除");
		}else{
			option.delete();
			success();
		}
		
	}

	@Log("生成投票选项")
	@AuthAnno
	@Before(Tx.class)
	public void autoOption() {
		int age = getParaToInt("user_age");
		String[] professional = getParaValues("user_professional");
		String vote_id = getPara("vote_id");
		String sex = getPara("user_sex");
		List<ExtUser> user = ExtUser.dao.findUser(age, sex, professional);
		for (ExtUser extUser : user) {
			ExtVoteOption op = new ExtVoteOption();
			op.set("name", extUser.getStr("user_name"));
			op.set("vote_id", vote_id);
			op.set("id", ExtKit.UUID());
			op.save();
		}
		success();
	}

	/*
	 * 根据id获取一条投票选项数据
	 */
	public void getOption() {
		ExtVoteOption option = ExtVoteOption.dao.findById(getPara("id"));
		renderJson(new Record().set("success", true).set("data", option));
	}

	/**
	 * 获取对应的选项按钮组
	 */
	public void optionjson() {
		String vote_id = getSessionAttr("vote_id");
		List<RadioBean> radiogroups = new ArrayList<RadioBean>();
		List<ExtVoteOption> pageData = ExtVoteOption.dao.findByAttr("vote_id",
				vote_id);
		for (ExtVoteOption extVoteOption : pageData) {
			RadioBean radio = new RadioBean();
			radio.setBoxLabel(extVoteOption.getStr("name"));
			radio.setName("option_id");
			radio.setInputValue(extVoteOption.getStr("id"));
			radio.setOrder(extVoteOption.getInt("order"));
			radiogroups.add(radio);
		}
		Collections.sort(radiogroups);
		renderJson(radiogroups);
	}
}
